package sfy.md.netty.netty;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

public class EchoClient {

    private final String host;
    private final int port;

    public EchoClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //为客户端创建引导
            Bootstrap b = new Bootstrap();                               //#1
            //指定EventLoopGroup去处理客户端事件.NioEventLoopGroup被使用,因为应该使用NIO-传输

                b.group(group)                                               //#2
                        //指定channel类型;使用正确的一个用于NIO-传输
                        .channel(NioSocketChannel.class)                     //#3
                        //设置客户端连接的InetSocketAddress
                        .remoteAddress(new InetSocketAddress(host, port)) ;   //#4

                        //指定ChannelHandler,使用ChannelInitializer,一旦连接建立被建立然后通道被创建
                        b.handler(new ChannelInitializer<SocketChannel>() {          //#5
                            @Override
                            public void initChannel(SocketChannel ch)
                                    throws Exception {
                                // 将EchoClientHandler加入到ChannelPipeline所属的通道上.
                                // ChannelPipeline保存了通道所有的ChannelHandlers
                                ch.pipeline().addLast(
                                        new EchoClientHandler());            //#6
                            }
                        });



            //连接客户端到远程端;等待直到sync()完成连接
            for(int i = 0;i<100;i++){

                ChannelFuture f = b.connect().sync();

                //等待直到ClientChannel关闭.这个将阻塞.
                f.channel().closeFuture().sync();
            }

        } finally {
            //关闭引导和线程池;释放所有的资源
            group.shutdownGracefully().sync();                           //#9
        }
    }

    public static void main(String[] args) throws Exception {

        new EchoClient("127.0.0.1", 8080).start();
//        new EchoClient("127.0.0.1", 8080).start();
//        new EchoClient("127.0.0.1", 8080).start();
//        new EchoClient("127.0.0.1", 8080).start();
    }
}


